package com.efrei.uchat.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.SocketException;
import java.util.Observable;

import org.apache.log4j.Logger;

import com.efrei.uchat.exception.UChatException;
import com.efrei.uchat.message.Message;

/**
 * Listen messages from server and dispatch them to observers
 */
public class ServerListener extends Observable implements Runnable {
	
	private static Logger logger = Logger.getLogger(ServerListener.class);
	
	private BufferedReader input;
	
	public ServerListener(Socket client) throws IOException {
		this.input = new BufferedReader(
				new InputStreamReader(client.getInputStream())
				);
	}
	
	@Override
	public void run() {
		logger.info("ServerListener running");
		
		// read messages
		try {
			readMessages();
		} catch(SocketException e) {
			logger.error("ServerListener: "+e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (UChatException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		// send null to notify disconnect
		setChanged();
		notifyObservers(null);
		deleteObservers();
		
		logger.info("end of ServerListener");
	}

	private void readMessages() throws IOException, UChatException {
		Message message;
		String data;
		
		while((data = input.readLine()) != null) {
			message = Message.fromString(data);
			manageMessage(message);
		}
	}

	private void manageMessage(Message message) {
		setChanged();
		notifyObservers(message);
	}
}
